//################################
// 版权所有：中国农业银行软件开发中心
// 系统名称：移动办公应用-手机版
// 文件名称：index.js
// 创建时间：2016年07月10日
// 创建人员：Panda
// 功能说明：附件组件
//################################

'use strict';

import React, {Component, PropTypes} from 'react';
import {
    StyleSheet,
    Image,
    ScrollView,
    Text,
    View,
    TouchableOpacity,
    InteractionManager,
} from 'react-native';

import {
    Colors,
    FontSizes,
    CommonFunc,
    CommonData,
    UIConstants,
    PubSubTopics,
} from '../../common';

import { getZhsoiAttachmentDetail } from '../../actions';

import ChildAttachment from './childAttachment';
import Images from '../../images';
import Icon from 'react-native-vector-icons/FontAwesome';
import { SwipeRow } from 'react-native-swipe-list-view';
import PubSub from 'pubsub-js';
import UUID from 'react-native-uuid';

const AttachmentFileType = [
    'zip',
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'jpg',
    'jpeg',
    'png',
    'bmp',
    'wps',
    'et',
    'dps',
    'pdf',
    'gif',
];

const ICON_SIZE = 25;

class Attachment extends Component {
    static propTypes = {
		attachment: PropTypes.object.isRequired,
        onPress: PropTypes.func.isRequired,
	}

    static defaultProps = {
		attachment: {},
        onPress: () => null,
    }

    constructor(props) {
        super(props);

        this.attachment = props.attachment?props.attachment:null;
        this.editorType = props.editorType?props.editorType:false;
        this.isUnZipped = false;
        this.isChildAttachmentsShow = false;
        this.isClicked = false;

        this.uuid = UUID.v1();

        this.init();
    }

    componentDidMount() {
        this.onAttachmentSwipeOpenEvent = PubSub.subscribe(PubSubTopics.ATTACHMENT_SWIPE_OPEN, (event, uuid) => {this.onAttachmentSwipeOpenHandler(uuid)});
    }
    
    componentWillUnmount() {
        PubSub.unsubscribe(this.onAttachmentSwipeOpenEvent);
    }
    
    onAttachmentSwipeOpenHandler(uuid) {
        if (this.uuid !== uuid) {
            this.swipeRow && this.swipeRow.closeRow();
        }
    }

    componentWillReceiveProps(nextProps) {
        this.attachment = nextProps.attachment;
        this.init();
    }
    
    init() {
        this.iconName = this.getIconName();
        this.fileName = this.attachment.fileName;
        this.fileSize = this.getFileSize();
        this.isZipFile = this.getIsZipFile();

        if (this.attachment.childAttachments && this.attachment.childAttachments.fileList) {
            if (this.isClicked) {
                this.isChildAttachmentsShow = true;
                this.isClicked = false;

                this.childAttachmentsInfo = this.getChildAttachmentsInfo();
            }
        }

        this.setState({});
    }

    getChildAttachmentsInfo() {
        let childAttachmentsInfo = UIConstants.attachment.childAttachmentsInfo.replace('{COUNTS}', this.attachment.childAttachments.totalCount);
        return childAttachmentsInfo;
    }

    getIsZipFile() {
        return this.attachment.fileName.toLowerCase().substring(this.attachment.fileName.lastIndexOf(".") + 1, this.attachment.fileName.length) === 'zip';
    }

    getFileSize() {
        let _fileSize = CommonFunc.getFileSizeStr(parseInt(this.attachment.fileSize));
        // if (_fileSize && _fileSize.length && _fileSize.length > 0) {
        //     _fileSize = '(' + _fileSize + ')';
        // }
        return _fileSize;
    }
    
    getIconName() {
        let suffix = this.attachment.fileName.toLowerCase();
        suffix = suffix.substring(suffix.lastIndexOf(".") + 1, suffix.length);

        let iconName = 'file-text-o';//默认的附件图标

        switch (suffix) {
            case 'zip':
                iconName = 'file-zip-o';
                break;
            case 'doc':
                iconName = 'file-word-o';
                break;
            case 'docx':
                iconName = 'file-word-o';
                break;
            case 'xls':
                iconName = 'file-excel-o';
                break;
            case 'xlsx':
                iconName = 'file-excel-o';
                break;
            case 'ppt':
                iconName = 'file-powerpoint-o';
                break;
            case 'pptx':
                iconName = 'file-powerpoint-o';
                break;
            case 'jpg':
                iconName = 'file-image-o';
                break;
            case 'jpeg':
                iconName = 'file-image-o';
                break;
            case 'png':
                iconName = 'file-image-o';
                break;
            case 'bmp':
                iconName = 'file-image-o';
                break;
            case 'wps':
                iconName = 'file-word-o';
                break;
            case 'et':
                iconName = 'file-excel-o';
                break;
            case 'dps':
                iconName = 'file-powerpoint-o';
                break;
            case 'pdf':
                iconName = 'file-pdf-o';
                break;
            case 'gif':
                iconName = 'file-image-o';
                break;
            default:
                break;
        }

        return iconName;
    }

    _onPress() {
        InteractionManager.runAfterInteractions(() => {
            this.closeSwipeOpen();

            if (this.fileName.lastIndexOf('.zip') > 0) {
                // 是压缩包
                if (this.attachment.childAttachments && this.attachment.childAttachments.fileList) {
                    // 压缩包是已经解压过的了
                    // 判断当前的显示状态，未显示则显示，已显示则不显示
                    this.isChildAttachmentsShow = !this.isChildAttachmentsShow;
                    this.childAttachmentsInfo = this.getChildAttachmentsInfo();
                    this.setState({});
                }
                else {
                    // 压缩包未解压
                    // 标记当前的附件被点击了
                    this.isClicked = true;
                    // 让父组件执行解压缩操作
                    this.props.onPress && this.props.onPress(this.attachment);
                }
            }
            else {
                this.downloadFileForRead();
                // 不是压缩包，让父组件处理附件显示的页面跳转
                // this.props.onPress && this.props.onPress(this.attachment);
            }
        });
	}

    _onDeletePress(){
        PubSub.publish(PubSubTopics.EMAIL_ATTACH_DELETE, this.attachment);
    }


    _onUnPress(){
        alert('dot touch it');
        
    }

    _onChildAttachmentPress(childAttachment) {
        // 不是压缩包，让父组件处理附件显示的页面跳转
        this.props.onPress && this.props.onPress(childAttachment);
    }

    getChildAttachments() {
        let childAttachments = this.attachment.childAttachments && this.attachment.childAttachments.fileList ? this.attachment.childAttachments.fileList : null;

        if (childAttachments) {
            let childAttachmentsItems = [];
            childAttachments.map((item, i) => {
                childAttachmentsItems.push(this.getChildAttachmentsItem(item));
            });

            return childAttachmentsItems;
        }
        else {
            return null;
        }
    }

    getChildAttachmentsItem(item) {
        return (
            <View>
                <ChildAttachment attachment={item} onPress={(attachment) => {this._onChildAttachmentPress(attachment)}} />
            </View>

        );
    }

    onHiddenButtonPressed() {
        //close the swipe when the downloadedPicsForRead is Pressed, P.S. the closeRow() is a internal method for swipeRow
        this.swipeRow && this.swipeRow.closeRow();
        this.downloadPicsForRead();
    }

    downloadFileForRead() {
        let fileName = this.attachment.fileName;
        let canBeDownloaded = false;

        //判断要下载的文件是不是符合文件类型
        for (let i = 0;i < CommonData.downloadFileTypeList.length;i++) {
            let item = CommonData.downloadFileTypeList[i];
            if( fileName.toLowerCase().lastIndexOf('.' + item) > 0 && fileName.toLowerCase().lastIndexOf('.' + item) === (fileName.length - item.length - 1)){
                canBeDownloaded = true;
                break;
            }
        }

        if (canBeDownloaded) {
            PubSub.publish(PubSubTopics.ATTACHMENT_SWIPE_OPEN, '');
            PubSub.publish(PubSubTopics.ATTACHMENT_DOWNLOAD_MODAL_OPEN, this.attachment);
        }
        else {
            PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, UIConstants.download.fileTypeNotSupported);
        }
    }

    downloadPicsForRead() {
        this.props.onPress && this.props.onPress(this.attachment);
    }

    onRowOpen() {
        this.closeSwipeOpen();
    }

    closeSwipeOpen() {
        PubSub.publish(PubSubTopics.ATTACHMENT_SWIPE_OPEN, this.uuid);
    }

    getAttachmentItem() {
        if (this.isZipFile) {
            return (
                <View style={styles.view}>
                    <TouchableOpacity style={styles.container} onPress={this._onPress.bind(this)}>
                        <View style={styles.attachmenticon} >
                            <Icon name={this.iconName} size={ICON_SIZE} color={Colors.white} />
                        </View>
                        <ScrollView>
                            <Text style={styles.attachmentnametext}>{this.fileName}</Text>
                            <Text style={styles.sizeText}>{this.isChildAttachmentsShow?this.childAttachmentsInfo:this.fileSize}</Text>
                        </ScrollView>
                    </TouchableOpacity>
                    {
                        this.isChildAttachmentsShow ? this.getChildAttachments() : null
                    }
                </View>
            );
        }
        else {
            return (
                <SwipeRow ref={(ref) => {this.swipeRow = ref}} rightOpenValue={-80} closeOnRowPress={true} disableRightSwipe={this.editorType} disableLeftSwipe={this.editorType} recalculateHiddenLayout={true} onRowOpen={() => {this.onRowOpen()}}>
                    <View style={styles.hiddenview}>
                        <TouchableOpacity style={styles.hiddenbutton} onPress={() => {this.onHiddenButtonPressed()}}>
                            <Text style={styles.hiddenbuttontext}>{UIConstants.attachment.picsForRead}</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.otherview}>
                        <TouchableOpacity style={styles.container} onPress={this.editorType ? ()=>null : this._onPress.bind(this)}>
                            <View style={styles.attachmenticon} >
                                <Icon name={this.iconName} size={ICON_SIZE} color={Colors.white} />
                            </View>
                            <ScrollView>
                                <Text style={styles.attachmentnametext}>{this.fileName}</Text>
                                <Text style={styles.sizeText}>{this.isChildAttachmentsShow?this.childAttachmentsInfo:this.fileSize}</Text>
                            </ScrollView>
                        </TouchableOpacity>
                        { 
                            this.editorType ?
                            <TouchableOpacity style={styles.draftboxcontainer} onPress={this._onDeletePress.bind(this)}>
                                <Image source={Images.EmailDraftBox} style={styles.contentright} resizeMode={Image.resizeMode.contain} /> 
                            </TouchableOpacity>
                            :
                            <View />
                        }
                    </View>
                </SwipeRow>
            );
        }
    }

    render() {
        return this.getAttachmentItem();
    }
}

// <Image source={icon} style={styles.attachmenticon} resizeMode={Image.resizeMode.contain} />

const styles = StyleSheet.create({
    view: {
        flex: 1,
        //flexDirection: 'row',
        backgroundColor: Colors.attachmentBackground,
    },
    otherview:  {
        flex: 1,
        flexDirection: 'row',
        backgroundColor: Colors.attachmentBackground,
        justifyContent: 'center',
        alignItems: 'center',
    },
    container: {
        flex:1,
        flexDirection: 'row',
        paddingLeft: 12,
        paddingRight: 12,
        alignItems: 'center',
        justifyContent:'center',
        marginTop: 5,
        marginBottom: 5,
    },
    attachmenticon:{
        alignItems:'center',
        justifyContent:'center',
        width:35,
        height:35,
        backgroundColor:'#6A9AC6'
    },
    attachmentnametext: {
        flex: 1,
        marginLeft: 10,
        color: Colors.attachmentFileName,
        fontSize:15
    },
    attachmentseparator: {
        height: 0.5,
        backgroundColor: Colors.gray,
    },
    sizeText:{
        fontSize:11,
        marginLeft:10
    },
    hiddenview: {
        flex: 1,
    },
    hiddenbutton: {
        alignItems: 'center',
        bottom: 0,
        top: 0,
        right: 0,
        width: 80,
        justifyContent: 'center',
        position: 'absolute',
        backgroundColor: Colors.attachmentBackButtonBackground,
    },
    hiddenbuttontext: {
        fontSize: FontSizes.attachmentBackButtonText,
        color: Colors.attachmentBackButtonText,
    },
     contentright: {
        width: 20,
        height: 20,
    },
     draftboxcontainer: {
        padding: 12,
        alignItems: 'flex-end',
        // borderWidth: 1,
        // borderColor: 'red',
    },
});

export default Attachment;